#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "FWDotView.h"


static CGFloat const pi = 3.14159;


@implementation FWDotView

@synthesize color;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)frame shadow:(BOOL)drawShadow
{
    if ((self = [super initWithFrame:frame])) {
        self.clipsToBounds = NO;
        shadow = drawShadow;
        self.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [self initWithFrame:frame shadow:NO])) {
    }
    
    return self;
}

- (void)dealloc
{
    [color release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Attribute access

- (void)setColor:(UIColor*)newColor
{
    if (color == newColor)
        return;
    
    if (newColor && color && [newColor isEqual:color])
        return;
    
    [newColor retain];
    [color release];
    color = newColor;
    
    [self setNeedsDisplay];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Drawing

- (void)drawGloss:(CGRect)rect
{
    NSString* file;
    if (rect.size.width >= 16)
        file = shadow ? @"gloss18-shadow" : @"gloss18";
    else if (rect.size.width >= 13)
        file = @"gloss13";
    else if (rect.size.width >= 10)
        file = @"gloss10";
    else
        file = shadow ? @"gloss9-shadow" : @"gloss9";

    UIImage* gloss = [UIImage imageWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:file ofType:@"png"]];
    [gloss drawInRect:rect];
}

- (void)drawRect:(CGRect)rect withGloss:(BOOL)gloss
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    
    [color set];
    CGContextFillEllipseInRect(ctx, rect);
    CGContextRestoreGState(ctx);

    if (gloss)
        [self drawGloss:rect];
}

- (void)drawRect:(CGRect) rect
{
    [self drawRect:rect withGloss:YES];
}

@end
